package Java_proxy;

/*动态代理举例*/

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface Human{
    String getBelief();
    void eat(String food);
}

// 被代理类
class Superman implements Human {

    @Override
    public String getBelief() {
        return "I believe I can fly";
    }

    @Override
    public void eat(String food) {
        System.out.println("超人喜欢吃" + food);
    }
}

// 代理类
class ProxyFactory{

    public static Object getProxyInstance(Object obj){
        MyInvocationHandler invocationHandler = new MyInvocationHandler();
        invocationHandler.bind(obj);

        return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
                obj.getClass().getInterfaces(),
                invocationHandler);
    }
}

class MyInvocationHandler implements InvocationHandler{

    private Object obj;

    public void bind(Object o){
        this.obj = o;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        HumanUtil humanUtil = new HumanUtil();
        humanUtil.method1();
        Object returnValue = method.invoke(obj, args);
        humanUtil.method2();
        return returnValue;
    }
}

class HumanUtil{

    public void method1(){
        System.out.println("===========通用方法一==============");
    }

    public void method2(){
        System.out.println("===========通用方法二==============");
    }
}

public class ProxyTest {
    public static void main(String[] args) {
        Superman superman = new Superman();
        Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superman);
        String belief = proxyInstance.getBelief();
        System.out.println(belief);
        proxyInstance.eat("四川麻辣烫");

        System.out.println();
        NikeClothFactory nike = new NikeClothFactory();
        ClothFactory proxy = (ClothFactory) ProxyFactory.getProxyInstance(nike);
        proxy.produceCloth();
    }
}
